package com.sixmac.platform.controller;

import com.sixmac.common.base.BaseController;
import com.sixmac.common.model.system.User;
import com.sixmac.core.plugins.dao.Blade;
import com.sixmac.core.plugins.dao.Md;
import com.sixmac.core.shiro.ShiroKit;
import com.sixmac.core.toolbox.Paras;
import com.sixmac.core.toolbox.ajax.AjaxResult;
import com.sixmac.core.toolbox.kit.DateKit;
import com.sixmac.core.toolbox.kit.JsonKit;
import com.sixmac.module.*;
import com.sixmac.platform.service.TenantService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.List;

/**
 * TenantController
 * 2018-09-11 20:12:57
 * @author Blade
 */
@Controller
@RequestMapping("/landlordTenant")
public class LandlordTenantController extends BaseController {
	private static String CODE = "landlordTenant";
	private static String PREFIX = "t_tenant";
	private static String LIST_SOURCE = "tenant.list2";
	private static String BASE_PATH = "/platform/landlordTenant/";
	
	@Autowired
	TenantService service;
	
	@RequestMapping(KEY_MAIN)
	public String index(ModelMap mm) {
		mm.put("code", CODE);
		return BASE_PATH + "tenant.html";
	}

	@RequestMapping(KEY_ADD)
	public String add(ModelMap mm) {
		mm.put("code", CODE);
		mm.put("id",getParameterToInt("id"));
		return BASE_PATH + "tenant_add.html";
	}

	@RequestMapping(KEY_EDIT + "/{id}")
	public String edit(@PathVariable Integer id, ModelMap mm) {
		Tenant tenant = service.findById(id);
		mm.put("model", JsonKit.toJson(tenant));
		mm.put("id", id);
		mm.put("code", CODE);
		return BASE_PATH + "tenant_edit.html";
	}

	@RequestMapping(KEY_VIEW + "/{id}")
	public String view(@PathVariable Integer id, ModelMap mm) {
		Tenant tenant = service.findById(id);
		mm.put("model", JsonKit.toJson(tenant));
		mm.put("id", id);
		mm.put("code", CODE);
		return BASE_PATH + "tenant_view.html";
	}

	@ResponseBody
	@RequestMapping(KEY_LIST)
	public Object list() {
		Object userId = ShiroKit.getUser().getId();
		User user = Blade.create(User.class).findById(Integer.valueOf(userId.toString()));
		Paras paras = Paras.create().set("phone",user.getAccount());
		Object grid = paginate(Md.getSql(LIST_SOURCE,paras));
		return grid;
	}

	@ResponseBody
	@RequestMapping(KEY_SAVE)
	public AjaxResult save() {
		Object userId = ShiroKit.getUser().getId();
		User user = Blade.create(User.class).findById(Integer.valueOf(userId.toString()));
		Landlord landlord = Blade.create(Landlord.class).findFirstBy(" mobile = '"+user.getAccount()+"'",null);

		String name = getParameter("t_tenant.name");
		String sex = getParameter("t_tenant.sex");
		String contract = getParameter("t_tenant.contract");
		String phone = getParameter("t_tenant.mobile");
		String idCard = getParameter("t_tenant.idCard");
		String idCardFront = getParameter("t_tenant.idCardFront");
		String idCardReverse = getParameter("t_tenant.idCardReverse");
		String startDate = getParameter("t_tenant.startDate");
		String endDate = getParameter("t_tenant.endDate");
		Integer roomId = getParameterToInt("roomId");

		Contract contract1 = new Contract();
		contract1.setContract(contract);
		contract1.setStartTime(DateKit.parseTime(startDate+" 00:00:00"));
		contract1.setEndTime(DateKit.parseTime(endDate+" 23:59:59"));
		contract1.setIdCard(idCard);
		contract1.setName(name);
		contract1.setSex(Integer.parseInt(sex));
		contract1.setMobile(phone);
		contract1.setIdCardFront(idCardFront);
		contract1.setIdCardReverse(idCardReverse);

		Room room = Blade.create(Room.class).findById(roomId);
		if (room == null)
			return error("房屋找不到");

		Tenant t = Blade.create(Tenant.class).findFirstBy("mobile=#{mobile}", getData("mobile", phone));
		//如果找不到手机号码，表示
		if (t == null) {
			//创建租户
			t = new Tenant();
			t.setIdCard(contract1.getIdCard());
			t.setIdCardFront(contract1.getIdCardFront());
			t.setIdCardReverse(contract1.getIdCardReverse());
			t.setMobile(contract1.getMobile());
			t.setName(contract1.getName());
			t.setSex(contract1.getSex());
			t.setCreateDate(new Date());
			t.setStatus(1);
			Integer id = Blade.create(Tenant.class).saveRtId(t);
			t.setId(id);
		} else {
			contract1.setTentantId(t.getId());
		}

		TenantRoom tr = Blade.create(TenantRoom.class).findFirstBy(" status = 1 and tenantId ="+t.getId(),null);

		if (tr!=null){
			return error("该用户已经入住。");
		}

		tr = Blade.create(TenantRoom.class).findFirstBy(" approve = 3 and tenantId ="+t.getId(),null);

		if (tr!=null&&tr.getRoomId()!=roomId){
			return error("该用户已经申请其他房间。");
		}

		if (tr!=null&&tr.getRoomId()==roomId) {
			return error("该用户已经申请，请去审核。");
		}

		TenantRoom tenantRoom = new TenantRoom();
		tenantRoom.setContract(contract1.getContract());
		tenantRoom.setRoomId(roomId);
		tenantRoom.setTenantId(t.getId());
		tenantRoom.setLandlordId(landlord.getId());
		tenantRoom.setCreateDate(new Date());
		tenantRoom.setStartDate(DateKit.parseTime(startDate+" 00:00:00"));
		tenantRoom.setEndDate(DateKit.parseTime(endDate+" 23:59:59"));
		tenantRoom.setApprove(1);
		tenantRoom.setStatus(1);
		tenantRoom.setKey(room.getKey() == null ? "" : room.getKey());
		Integer ids = Blade.create(TenantRoom.class).saveRtId(tenantRoom);

		contract1.setStartTime(tenantRoom.getStartDate());
		contract1.setEndTime(tenantRoom.getEndDate());
		contract1.setTenantRoomId(ids);
		contract1.setHandCard(t.getHandCard());
		contract1.setStatus(0);//入住
		contract1.setTentantId(t.getId());
		contract1.setRoomId(room.getId());
		Blade.create(Contract.class).save(contract1);
//		boolean temp = service.save(tenant);
//		if (temp) {
//			return success(SAVE_SUCCESS_MSG);
//		} else {
//			return error(SAVE_FAIL_MSG);
//		}
		return success(SAVE_SUCCESS_MSG);
	}

	@ResponseBody
	@RequestMapping(KEY_UPDATE)
	public AjaxResult update() {
		Tenant tenant = mapping(PREFIX, Tenant.class);
		boolean temp = service.update(tenant);
		if (temp) {
			return success(UPDATE_SUCCESS_MSG);
		} else {
			return error(UPDATE_FAIL_MSG);
		}
	}

	@ResponseBody
	@RequestMapping(KEY_REMOVE)
	public AjaxResult remove(@RequestParam String ids) {
		List<TenantRoom> tenantRooms = Blade.create(TenantRoom.class).findBy("tenantId in("+ids+") and status = 1",null);
		if (tenantRooms.size()>0){
			return error("删除失败，选择的租户已入住");
		}
		int cnt = service.deleteByIds(ids);
		Blade.create(TenantRoom.class).deleteBy("tenantId in("+ids+")",null);
		Blade.create(Contract.class).deleteBy("tentantId in("+ids+")",null);
		if (cnt > 0) {
			return success(DEL_SUCCESS_MSG);
		} else {
			return error(DEL_FAIL_MSG);
		}
	}
}
